import { useStore } from 'vuex';
import { computed } from 'vue';
import { save, remove } from '../../assets/js/array-store';
import { FAVORITE_KEY } from '../../assets/js/constant';

export default function useFavorite() {
  const store = useStore();
  const favoriteList = computed(() => store.state.favoriteList);
  const maxLen = 100;

  // 判断当前歌曲收藏图标
  function getFavoriteIcon(song) {
    return isFavorite(song) ? 'icon-favorite' : 'icon-not-favorite';
  }

  // 收藏按钮点击
  function toggleFavorite(song) {
    let list;
    if (isFavorite(song)) {
      // 如果歌曲已存在,则删除
      list = remove(FAVORITE_KEY, compare);
    } else {
      // 如果歌曲不在,则添加
      list = save(song, FAVORITE_KEY, compare, maxLen);
    }
    store.commit('setFavoriteList', list);

    function compare(item) {
      return item.id === song.id;
    }
  }

  // 判断当前歌曲是否被收藏
  function isFavorite(song) {
    return favoriteList.value.findIndex(item => {
      return item.id === song.id;
    }) > -1;
  }

  return {
    getFavoriteIcon,
    toggleFavorite
  };
}
